<?php
/*
 Plugin Name: vlogMonkey
 Plugin URI: http://www.rudyjahchan.com/code/vlogmonkey/
 Description: A video blogging plug-in.
 Version: 1.0
 Author: Rudy Jahchan
 Author URI: http://www.rudyjahchan.com
 */

add_option("vmonk_allowmediafiltering", true, "Flags if we support media filtering.", true);
add_option("vmonk_allowplatformfiltering", true, "Flags if we support platform filtering.", true);
add_option("vmonk_addmediarss", true, "Add Media RSS elements", true);
add_option("vmonk_adddownloadstofeed", "No", "Add downlod links for a posts enclosure to the feed entries.", true);
add_option("vmonk_adddownloadstofeed_beforealllinks", "Downloads:", "", true);
add_option("vmonk_adddownloadstofeed_afteralllinks", "", "", true);
add_option("vmonk_adddownloadstofeed_beforeeachlink", "|", "", true);
add_option("vmonk_adddownloadstofeed_aftereachlink", "", "", true);

function vmonk_optionspage() {
	if (isset ($_POST['info_update'])) {
		if (isset ($_POST['vmonk_allowmediafiltering'])) {
			update_option('vmonk_allowmediafiltering', ($_POST['vmonk_allowmediafiltering'] == "true")) ;
		} else {
			update_option('vmonk_allowmediafiltering', false) ;
		}

		if (isset ($_POST['vmonk_allowplatformfiltering'])) {
			update_option('vmonk_allowplatformfiltering', ($_POST['vmonk_allowplatformfiltering'] == "true")) ;
		} else {
			update_option('vmonk_allowplatformfiltering', false) ;
		}

		if (isset ($_POST['vmonk_allowplatformfiltering'])) {
			update_option('vmonk_allowplatformfiltering', ($_POST['vmonk_allowplatformfiltering'] == "true")) ;
		} else {
			update_option('vmonk_allowplatformfiltering', false) ;
		}

		if (isset ($_POST['vmonk_adddownloadstofeed'])) {
			update_option('vmonk_adddownloadstofeed', $_POST['vmonk_adddownloadstofeed']) ;
			
			if ($_POST['vmonk_adddownloadstofeed'] != "No") {
				if (isset ($_POST['vmonk_adddownloadstofeed_beforealllinks'])) {
					update_option('vmonk_adddownloadstofeed_beforealllinks', $_POST['vmonk_adddownloadstofeed_beforealllinks']) ;
				}
		
				if (isset ($_POST['vmonk_adddownloadstofeed_afteralllinks'])) {
					update_option('vmonk_adddownloadstofeed_afteralllinks', $_POST['vmonk_adddownloadstofeed_afteralllinks']) ;
				}
		
				if (isset ($_POST['vmonk_adddownloadstofeed_beforeeachlink'])) {
					update_option('vmonk_adddownloadstofeed_beforeeachlink', $_POST['vmonk_adddownloadstofeed_beforeeachlink']) ;
				}
		
				if (isset ($_POST['vmonk_adddownloadstofeed_aftereachlink'])) {
					update_option('vmonk_adddownloadstofeed_aftereachlink', $_POST['vmonk_adddownloadstofeed_aftereachlink']) ;
				}
			}
		}

	}

	echo '<style types="text/css">';
	echo '#vmonk_options div.spacer { clear: both;}';
	echo '#vmonk_options label.vmonk_label { display:block; width: 33%; text-align: right; float: left;}';
	echo '#vmonk_options .vmonk_text { display:block; width: 66%; text-align: left; float: left;}';
	echo '</style>';
	echo '<div id="vmonk_options" class="wrap">';
	echo '<h2>Vlog Monkey!</h2>';
	echo '<form method="post" action="">';
	echo '<input type="hidden" name="info_update" value="1" />';
	echo '<fieldset class="options">';
	echo '<label><input type="checkbox" name="vmonk_allowmediafiltering" value="true" ' . ( get_option("vmonk_allowmediafiltering") ? 'checked="checked"': '') . '/>Allow filtering of enclosures by <code>media</code> parameter</label><br />';
	echo '<label><input type="checkbox" name="vmonk_allowplatformfiltering" />Allow filtering of enclosures by <code>platform</code> parameter</label>';
	echo '</fieldset>';

	echo '<fieldset class="options">';
	echo '<label><input type="checkbox" name="vmonk_addmediarss" />Add Media RSS tags to feeds.</label><br />';
	echo '</fieldset>';

	echo '<fieldset class="options">';
	echo '<label>Add download links to feeds: <select name="vmonk_adddownloadstofeed" id="vmonk_adddownloadstofeed">';
	echo '<option value="No" ' . (get_option("vmonk_adddownloadstofeed") == "No" ? 'selected="selected"' : '') . '>No</option>';
	echo '<option value="Before" ' . (get_option("vmonk_adddownloadstofeed") == "Before" ? 'selected="selected"' : '') . '>Before</option>';
	echo '<option value="After" ' . (get_option("vmonk_adddownloadstofeed") == "After" ? 'selected="selected"' : '') . '>After</option>';
	echo '</select></label>';
	
	echo '<div id="vmonk_downloadlinkwrappers">';
	echo '<div class="spacer"></div>';
	echo '<label class="vmonk_label" for="vmonk_adddownloadstofeed_beforealllinks">Before all links write:</label><input class="vmonk_text" id="vmonk_adddownloadstofeed_beforealllinks" name="vmonk_adddownloadstofeed_beforealllinks" value="'.  stripslashes(get_option('vmonk_adddownloadstofeed_beforealllinks')) . '" type="text" />';
	echo '<label class="vmonk_label" for="vmonk_adddownloadstofeed_afteralllinks">After all links write:</label><input class="vmonk_text" id="vmonk_adddownloadstofeed_afteralllinks" name="vmonk_adddownloadstofeed_afteralllinks" value="'.  stripslashes(get_option('vmonk_adddownloadstofeed_afteralllinks')) . '" type="text" />';
	echo '<label class="vmonk_label" for="vmonk_adddownloadstofeed_beforeeachlink">Before each link write:</label><input class="vmonk_text" id="vmonk_adddownloadstofeed_beforeeachlink" name="vmonk_adddownloadstofeed_beforeeachlink" value="'.  stripslashes(get_option('vmonk_adddownloadstofeed_beforeeachlink')) . '" type="text" />';
	echo '<label class="vmonk_label" for="vmonk_adddownloadstofeed_aftereachlink">After each link write:</label><input class="vmonk_text" id="vmonk_adddownloadstofeed_aftereachlink" name="vmonk_adddownloadstofeed_aftereachlink" value="'.  stripslashes(get_option('vmonk_adddownloadstofeed_aftereachlink')) . '" type="text" />';
	echo '<div class="spacer"></div>';
	echo '<div class="vmonk_feedlinkpreview">';
	echo '</div>';
	echo '</fieldset>';

	echo '<div class="submit" style="text-align: right"><input type="submit" value="Update &raquo;&raquo;" /></div>';

	echo '</form>';
	echo '</div>';
	
	echo '<script type="text/javascript" src="' . get_settings('siteurl') . '/wp-includes/js/jquery/jquery.js"></script>';
	echo '<script type="text/javascript" src="' . get_settings('siteurl') . '/wp-content/plugins/vlogMonkey/js/vlogMonkeyOptions.js"></script>';
}

function vmonk_addadminpages() {
    add_options_page('Vlog Monkey', 'Vlog Monkey', 8, 'vlogMonkeyOptions', 'vmonk_optionspage');
}

function vmonk_generate_enclosureslinks($beforeAll="",$afterAll="",$beforeEach="",$afterEach="",$platforms=null,$mediaTypes=null) {
	$result = "";
	$enclosures = vmonk_get_enclosures($platforms,$mediaTypes);
	if ($enclosures != null && !empty($enclosures)) {
		if ($beforeAll != null) {
			$result .= $beforeAll;
		}
		
		foreach($enclosures as $enclosure) {
			if ($beforeEach != null) {
				$result .= $beforeEach;
			}
			
			$result .= "<a href=\"" . $enclosure['url'] . "\" type=\"" .$enclosure['media'] . "\" rel=\"enclsoure\">" . $enclosure['platform'] . "</a>";
			
			if ($afterEach != null) {
				$result .= $afterEach;
			}
		}
		
		if ($afterAll != null) {
			$result .= $afterAll;
		}
	}
	
	return $result;
}

function vmonk_addtofeed($content) {
	if (is_feed()) {
		$filteredContent = "";
		
		$beforeAll = get_option("vmonk_adddownloadstofeed_beforealllinks");
		$afterAll = get_option("vmonk_adddownloadstofeed_afteralllinks");
		$beforeEach = get_option("vmonk_adddownloadstofeed_beforeeachlink");
		$afterEach = get_option("vmonk_adddownloadstofeed_aftereachlink");
		$addToFeed = get_option("vmonk_adddownloadstofeed");
		
		if ($addToFeed == "Before") {
			$filteredContent .= vmonk_generate_enclosureslinks($beforeAll,$afterAll,$beforeEach,$afterEach);			
		}
		
		$filteredContent .= $content;
		
		if ($addToFeed == "After") {
			$filteredContent .= vmonk_generate_enclosureslinks($beforeAll,$afterAll,$beforeEach,$afterEach);			
		}
		
		return $filteredContent;
	} else {
		return $content;
	}

}

function vmonk_ns () {
	echo " xmlns:media=\"http://search.yahoo.com/mrss/\"";
}

function vmonk_mediarss() {
	$enclosures = vmonk_get_enclosures();
	$defaultSelected = false;
	
	$mediaTypes = null;
	$platforms = null;

	if (!empty ($_REQUEST['media'])) {
		$mediaTypes = split(",", $_REQUEST['media']);
	}

	if (!empty ($_REQUEST['platform'])) {
		$platforms = split(",", $_REQUEST['platform']);
	}
	 
	echo "<media:group>\n";
	foreach ($enclosures as $enclosure) {
		
		echo "\t<media:content url=\"" . $enclosure['url'] . "\" fileSize=\"" . $enclosure['length'] ."\" type=\"" . $enclosure['media'] ."\" ";

		if ($mediaTypes != null && !$defaultSelected) {
			if (in_array($enclosure['media'],$mediaTypes)) {
				$defaultSelected = true;
				echo "isDefault=\"true\" ";
			}
		}
		
		if ($platforms != null && !$defaultSelected) {
			if (in_array($enclosure['platform'],$platforms)) {
				$defaultSelected = true;
				echo "isDefault=\"true\" ";
			}
		}

		echo "/>\n";
	}
	echo "</media:group>\n";
}

function vmonk_get_enclosures_for_platforms($platforms) {
	return vmonk_get_enclosures($platforms, null);
}

function vmonk_get_enclosures_for_media($media) {
	return vmonk_get_enclosures(null, $media);	
}
 
function vmonk_get_enclosures($platforms=null,$media=null) {
	global $id;
	
	$enclosures = array();
	
	$enclosuresMeta = get_post_meta( $id, 'enclosure');
	
	foreach($enclosuresMeta as $enclosureMeta) {
		$enclosureLines = split("\n", $enclosureMeta);
		
		if ($platforms != null) {
			if ( !in_array(trim($enclosureLines[3]), $platforms) ) {
				continue;
			}
		}
		
		if ($media != null) {
			if ( !in_array(trim($enclosureLines[2]), $platforms) ) {
				continue;
			}
		}		
		
		$enclosure = array (
			'url' => trim($enclosureLines[0]), 
			'length' => trim($enclosureLines[1]),
			'media' => trim($enclosureLines[2]),
			'platform' => trim($enclosureLines[3]),
			'show' => trim($enclosureLines[4]),
			'width' => trim($enclosureLines[5]),
			'height' => trim($enclosureLines[6])
		);
		$enclosures[] = $enclosure;	
	}
	
	return $enclosures;
} 

function vmonk_enclosure_filter($enclosureElement) {
	global $id;
	
	$enclosureElementURL = "";
	$enclosureElementLength = "";
	$enclosureElementType = "";
	
	$matches = preg_match_all('/\s(href|url|length|type)="([^"]*)"/', $enclosureElement, $attributes, PREG_SET_ORDER);
	foreach ($attributes as $attribute) {
		if ($attribute[1] == "url" || $attribute[1] == "href") {
			$enclosureElementURL = $attribute[2];
		} else if ($attribute[1] == "length") {
			$enclosureElementLength = $attribute[2];
		} else if ($attribute[1] == "type") {
			$enclosureElementType = $attribute[2];
		}
	}
	
	// if we have a media parameter in the URL
	// skip if the enclosure's media and the paramter value do not match
	if (!empty ($_REQUEST['media']) && get_option("vmonk_allowmediafiltering")) {
		$mediaTypes = split(",", $_REQUEST['media']);
		
		if ( !in_array($enclosureElementType,$mediaTypes) ) {
			return "";
		}
	}

	// if we have a platform parameter in the URL
	// skip if the enclosure and media do not match
	if (!empty ($_REQUEST['platform'])) {
		$platforms = split(",", $_REQUEST['platform']);
		$filteredEnclosures = vmonk_get_enclosures($platforms);
		$found = false;
		
		foreach ($filteredEnclosures as $enclosure) {
			if ($enclosure['url'] == $enclosureElementURL) {
				$found = true;
			}
		}
		
		if (!$found) {
			return "";
		}
	}
	
	
	return $enclosureElement;
}

add_filter('rss_enclosure','vmonk_enclosure_filter');
add_filter('atom_enclosure','vmonk_enclosure_filter');
add_filter('the_content','vmonk_addtofeed');
add_filter('the_content_rss','vmonk_addtofeed');
add_action('rss2_ns','vmonk_ns');
add_action('atom_ns','vmonk_ns');
add_action('rss2_item','vmonk_mediarss');
add_action('atom_entry','vmonk_mediarss');
add_action('admin_menu', 'vmonk_addadminpages');
?>